using System;
using System.Threading;

namespace ThreadingPrimeNumberSample.Core
{
    public class PrimeEngine : IPrimeEngine
    {
        private int _currentNumber = 3;
        public bool Continue { get; set; }
        public event EventHandler<PrimeFoundEventArgs> PrimeFound = delegate { };

        public void GetNextPrimeValue()
        {
            Continue = true;
            while (Continue)
            {
                bool notAPrime = false;

                for (long i = 3;
                     i <= Math.Sqrt(_currentNumber);
                     i++)
                {
                    if (_currentNumber % i == 0)
                    {
                        notAPrime = true;
                        break;
                    }
                }

                if (!notAPrime)
                {
                    PrimeFound(this, new PrimeFoundEventArgs{ Prime = _currentNumber});
                    Thread.Sleep(1000);
                }

                _currentNumber += 2;
            }
        }
    }
}